package com.ruoyi.web.controller.system;

import com.ruoyi.alipay.domain.PaymentSettlement;
import com.ruoyi.alipay.service.PaymentSettlementService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 支付管理控制器
 */
@RestController
@RequestMapping("/system/payment")
public class PaymentController extends BaseController {

    @Autowired
    private PaymentSettlementService paymentSettlementService;

    /**
     * 查询支付列表
     */
    @PreAuthorize("@ss.hasPermi('system:payment:list')")
    @GetMapping("/list")
    public TableDataInfo list(PaymentSettlement payment) {
        startPage();
        List<PaymentSettlement> list = paymentSettlementService.selectPaymentList(payment);
        return getDataTable(list);
    }

    /**
     * 导出支付列表
     */
    @PreAuthorize("@ss.hasPermi('system:payment:export')")
    @Log(title = "支付管理", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(PaymentSettlement payment) {
        List<PaymentSettlement> list = paymentSettlementService.selectPaymentList(payment);
        ExcelUtil<PaymentSettlement> util = new ExcelUtil<>(PaymentSettlement.class);
        return util.exportExcel(list, "支付数据");
    }

    /**
     * 获取支付详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:payment:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(paymentSettlementService.selectPaymentById(id));
    }

    /**
     * 获取支付统计信息
     */
    @PreAuthorize("@ss.hasPermi('system:payment:query')")
    @GetMapping("/stats")
    public AjaxResult getStats() {
        // 获取支付统计数据
        List<PaymentSettlement> list = paymentSettlementService.selectPaymentList(new PaymentSettlement());
        
        // 统计总金额
        double totalAmount = list.stream()
                .filter(p -> "TRADE_SUCCESS".equals(p.getTradeStatus()) || "TRADE_FINISHED".equals(p.getTradeStatus()))
                .mapToDouble(p -> p.getTotalAmount().doubleValue())
                .sum();
        
        // 统计各状态的订单数量
        Map<String, Long> statusCount = list.stream()
                .collect(Collectors.groupingBy(PaymentSettlement::getTradeStatus, Collectors.counting()));
        
        // 构建返回结果
        AjaxResult result = AjaxResult.success();
        result.put("totalAmount", totalAmount);
        result.put("totalCount", list.size());
        result.put("statusCount", statusCount);
        
        return result;
    }
} 